package cn.edu.tju.elm.service;

import cn.edu.tju.elm.model.RewardRule;
import cn.edu.tju.elm.repository.RewardRuleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class RewardRuleServiceImpl implements RewardRuleService {

    @Autowired
    private RewardRuleRepository rewardRuleRepository;
    
    @Autowired
    private UserAuthorityService userAuthorityService;

    @Override
    public RewardRule getRewardRuleByAuthority(String authorityName) {
        return rewardRuleRepository.findByAuthorityNameAndIsActiveTrue(authorityName)
                .orElseGet(() -> createDefaultRuleForAuthority(authorityName));
    }

    @Override
    public RewardRule getRewardRuleByUserId(Long userId) {
        // 获取用户权限
        Set<String> authorities = userAuthorityService.getUserAuthorities(userId);
        
        // 优先检查商家权限
        if (userAuthorityService.isMerchant(userId)) {
            return getRewardRuleByAuthority("ROLE_MERCHANT");
        }
        
        // 默认使用普通用户规则
        return getDefaultUserRewardRule();
    }

    @Override
    public RewardRule getDefaultUserRewardRule() {
        return getRewardRuleByAuthority("ROLE_USER");
    }

    @Override
    public RewardRule getMerchantRewardRule() {
        return getRewardRuleByAuthority("ROLE_MERCHANT");
    }

    @Override
    public List<RewardRule> getAllRewardRules() {
        return rewardRuleRepository.findAll();
    }

    @Override
    @Transactional
    public RewardRule updateRewardRule(String ruleName, String authorityName, BigDecimal minRechargeAmount, 
                                      BigDecimal rewardAmount, BigDecimal rewardRate, BigDecimal withdrawFeeRate) {
        // 参数验证
        if (ruleName == null || ruleName.trim().isEmpty()) {
            throw new IllegalArgumentException("规则名称不能为空");
        }
        if (authorityName == null || authorityName.trim().isEmpty()) {
            throw new IllegalArgumentException("权限名称不能为空");
        }
        
        // 获取现有规则或创建新规则
        RewardRule rule = rewardRuleRepository.findByAuthorityName(authorityName)
                .orElseGet(() -> {
                    RewardRule newRule = new RewardRule();
                    newRule.setAuthorityName(authorityName);
                    newRule.setIsActive(true);
                    return newRule;
                });
        
        // 更新规则信息
        rule.setRuleName(ruleName);
        rule.setMinRechargeAmount(minRechargeAmount);
        rule.setRewardAmount(rewardAmount);
        rule.setRewardRate(rewardRate);
        rule.setWithdrawFeeRate(withdrawFeeRate);
        
        return rewardRuleRepository.save(rule);
    }

    @Override
    @Transactional
    public RewardRule updateRewardRule(String ruleName, BigDecimal minRechargeAmount, 
                                      BigDecimal rewardAmount, BigDecimal rewardRate, BigDecimal withdrawFeeRate) {
        // 兼容旧接口，默认更新普通用户规则
        return updateRewardRule(ruleName, "ROLE_USER", minRechargeAmount, rewardAmount, rewardRate, withdrawFeeRate);
    }

    @Override
    public RewardRule getRewardRule() {
        // 兼容旧接口，返回默认用户规则
        return getDefaultUserRewardRule();
    }

    /**
     * 根据权限名称创建默认规则
     */
    private RewardRule createDefaultRuleForAuthority(String authorityName) {
        RewardRule rule = new RewardRule();
        rule.setAuthorityName(authorityName);
        rule.setIsActive(true);
        
        switch (authorityName) {
            case "ROLE_MERCHANT":
                rule.setRuleName("默认商家规则");
                rule.setMinRechargeAmount(null); // 商家没有充值门槛
                rule.setRewardAmount(BigDecimal.ZERO);
                rule.setRewardRate(BigDecimal.ZERO); // 商家没有充值奖励
                rule.setWithdrawFeeRate(BigDecimal.valueOf(0.01)); // 商家提现手续费1%
                break;
            case "ROLE_USER":
            default:
                rule.setRuleName("默认用户规则");
                rule.setMinRechargeAmount(BigDecimal.ZERO);
                rule.setRewardAmount(BigDecimal.ZERO);
                rule.setRewardRate(BigDecimal.valueOf(0.10));
                rule.setWithdrawFeeRate(BigDecimal.valueOf(0.10));
                break;
        }
        
        return rewardRuleRepository.save(rule);
    }
}